import pandas as pd
import yaml

from yaml import SafeLoader

from datareport.api import ImageUtil
from datareport.api.DataSource import DataSource
from datareport.api.annotation.Font import Font
from datareport.api.enum.ColorEnum import ColorEnum
from datareport.impl.paragraph.base.BaseParagraph import BaseParagraph
from datareport.api.annotation.Style import style


@style()
class KaiZhanQingKuang_one_jiceng_36(BaseParagraph):
    """

    """
    decrease=40

    def __init__(self):
        super().__init__()
        self.text = ('''3、从基层党支部层面来看: {}%的党支部完成率达100%及以上。\
{}%的党支部完成率处于 100%-200%之间，达200%以上的有{}个，占比{}%，\
''')
        self.sort = 26
        self.section = 10

    def plot(self, df, plt):
        pass

    def getData(self, result):
        pass

    def start(self, conn, year, plt):
        plan=pd.read_sql('''select p.*,r.num num1 from (
        select partyBranchName, count(*) num from t_meetingplan  where isPlan=1 and completeStatus='通过'
        group by partyBranchName) p left join (select i.partyBranchName,count(1) num from t_meetingrecord r left join t_meetinginfo i on r.meetingInfoId=i.id where r.completeStatus='通过'
        group by i.partyBranchName) r on p.partyBranchName=r.partyBranchName
        ''',con=conn)
        plan=plan.fillna(0)
        plan['percent']=round(100*plan['num1']/plan['num'],1)
        self.text = self.text.format(round(100*len(plan[plan['percent']>=100])/len(plan),1),
                                     round(100 * len(plan[(plan['percent'] >= 100) & (plan['percent'] <= 200)]) / len(plan), 1),
                                     len(plan[(plan['percent'] > 200)]),
                                     round(100*len(plan[plan['percent']>200])/len(plan),1))
        self.fonts.append(Font(text=self.text))
        plan['bl']=plan['percent'].apply(bl)
        temp=plan['bl'].value_counts().reset_index(drop=False)
        labels=temp['index'].values.tolist()
        values=temp['bl'].values.tolist()
        title='基层党支部计划完成率分布'
        self.image=ImageUtil.pie(labels,values,title)

def bl(x):
    if x<100:
        return '100%以下'
    if 100<=x and x>200:
        return '100%-200%'
    if 200<=x and x>300:
        return '200%-300%'
    if 300<=x and x>400:
        return '300%-400%'
    if 400<=x and x>500:
        return '400%-500%'
    if x>=500:
        return '500%以上'

if __name__ == '__main__':
    with open('D:\work\sanhuiyike\datareport\config.yaml', encoding='utf-8') as f:
        data = yaml.load(f, Loader=SafeLoader)
    con=DataSource(data['datasource']).conn
    KaiZhanQingKuang_one_jiceng_36().start(con,2023,'')
